using System;
using System.Collections;
using Gtk;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace TracNghiem2
{
	public class DeThi
	{
		public DeThi ()
		{
			questions = new ArrayList ();
		}
		
		public ArrayList questions;

		public CauHoi get_question (int i)
		{
			return (CauHoi)questions [i];
		}


		public int add_question (CauHoi question)
		{
			questions.Add (question);
			return 1; /* FIXME */
		}

		public ArrayList get_database ()
		{
			return questions;
		}

		public int count ()
		{
			return questions.Count;
		}

		public int read_questions (string file_name)
		{
			/* FIXME : Test this ! */
			System.IO.FileStream file = System.IO.File.OpenRead (file_name);

			XPathDocument xml_file = new XPathDocument (file);

			XPathNavigator xNav = xml_file.CreateNavigator ();

			xNav.MoveToRoot ();
			xNav.MoveToFirstChild (); /* Move to DeThi element */

			xNav.MoveToFirstChild (); /* Move to first CauHoi element */

			CauHoi c;
			do {
				c = new CauHoi ();

				xNav.MoveToFirstAttribute ();
				c.question = xNav.Value;

				xNav.MoveToNextAttribute ();
				c.rigth_answer = xNav.Value;

				xNav.MoveToParent ();

				xNav.MoveToFirstChild ();
				Console.WriteLine (xNav.Name + "=" + xNav.Value);
				c.answer_a = xNav.Value;

				xNav.MoveToNext ();
				Console.WriteLine (xNav.Name + "=" + xNav.Value);
				c.answer_b = xNav.Value;

				xNav.MoveToNext ();
				Console.WriteLine (xNav.Name + "=" + xNav.Value);
				c.answer_c = xNav.Value;

				xNav.MoveToNext ();
				Console.WriteLine (xNav.Name + "=" + xNav.Value);
				c.answer_d = xNav.Value;

				xNav.MoveToParent ();

				questions.Add (c);
			} while (xNav.MoveToNext ());

			file.Close ();
			return 1; /* FIXME */
		}

		public int write_questions (string file_name)
		{
			System.IO.FileStream file = System.IO.File.OpenWrite (file_name);
			System.IO.TextWriter file_stream = new StreamWriter (file); /* FIXME: clean up */

			XmlTextWriter writer = new XmlTextWriter (file_stream);
			writer.Formatting = Formatting.Indented;
			writer.Indentation = 4;

			writer.WriteStartDocument ();
			writer.WriteStartElement ("DeThi");

			foreach (CauHoi question in questions) {
				writer.WriteStartElement ("CauHoi");
				writer.WriteAttributeString ("noiDung", question.question);
				writer.WriteAttributeString ("dapAnDung", question.rigth_answer);

				writer.WriteStartElement ("DapAnA");
				writer.WriteString (question.answer_a);
				writer.WriteEndElement ();

				writer.WriteStartElement ("DapAnB");
				writer.WriteString (question.answer_b);
				writer.WriteEndElement ();

				writer.WriteStartElement ("DapAnC");
				writer.WriteString (question.answer_c);
				writer.WriteEndElement ();

				writer.WriteStartElement ("DapAnD");
				writer.WriteString (question.answer_d);
				writer.WriteEndElement ();

				writer.WriteEndElement ();
			}

			writer.WriteEndElement ();
			file_stream.Close ();
			file.Close ();
			return 1; /* FIXME */
		}
	}
}

